package development.listener;

import java.util.Vector;

import state.socket.DataPackage;
import state.socket.MapDataPackage;
import development.Global;
import development.socket.ProtocolConstants;
import development.socket.SocketClientUtil;

public class SMSSystemCommandListener extends Listener {

  public SMSSystemCommandListener() {
    super(SMSSystemCommandListener.class.toString());
  }

  public void onConnectDone() {
    SocketClientUtil.requestSMSSystemCommand(Global.provider.getId());
  }

  public void onConnectFail() {
  }

  public void onDisconnect() {
  }

  public void onRecieveData(DataPackage dataPackage) {
    int header = dataPackage.getHeader();
    switch (header) {
    case ProtocolConstants.ResponseHeader.SMS_SYSTEM_COMMAND_RESPONSE:
      onSMSSystemCommandReceive(dataPackage);
      break;
    }
  }

  private void onSMSSystemCommandReceive(DataPackage dataPackage) {
    MapDataPackage mapDataPackage = MapDataPackage.getMapPackage(dataPackage);
    Vector serviceNames = mapDataPackage.getNames();
    for (int i = 0; i < serviceNames.size(); i++) {
      Global.smsCommand.put(serviceNames.elementAt(i), parseSMSCommand((String) mapDataPackage.get((String) serviceNames.elementAt(i))));
    }
    Global.authenticateHandle.removeListener(this);
  }

  private String[] parseSMSCommand(String s) {
    // RingTone DI,7785
    return split(s, ",");
  }
  private String[] split(String original, String separator) {
    Vector nodes = new Vector();
    int index = original.indexOf(separator);
    while (index >= 0) {
      nodes.addElement(original.substring(0, index));
      original = original.substring(index + separator.length());
      index = original.indexOf(separator);
    }
    nodes.addElement(original);
    String[] result = new String[nodes.size()];
    if (nodes.size() > 0)
      for (int loop = 0; loop < nodes.size(); loop++)
        result[loop] = (String) nodes.elementAt(loop);
    return result;
  }
}
